import { getLodop } from '@/assets/js/LodopFuncs'

// 导出excel
export function htmlToExcel(fileName, id) {
  //HTML导出excel
  const tableHtml = document.querySelector(`#${id}`).innerHTML
  const worksheet = 'Sheet1'
  const uri = 'data:application/vnd.ms-excel;base64,'
  // 下载的表格模板数据
  const template = `
                <html
                  xmlns:o="urn:schemas-microsoft-com:office:office"
                  xmlns:x="urn:schemas-microsoft-com:office:excel"
                  xmlns="http://www.w3.org/TR/REC-html40">
                  <head>
                    <meta charset="utf-8">
                      <!--[if gte mso 9]>
                      <xml>
                        <x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                        <x:Name>${worksheet}</x:Name>
                        <x:WorksheetOptions><x:DisplayGridlines/>
                        </x:WorksheetOptions></x:ExcelWorksheet>
                        </x:ExcelWorksheets></x:ExcelWorkbook>
                      </xml>
                      <![endif]-->
                  </head>
                  <body>
                    <table border="1">${tableHtml}</table>
                  </body>
                </html>
              `

  // 下载模板
  const a = document.createElement('a')
  const event = new MouseEvent('click')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template))) // 之所以这样写是为了防止出现中文乱码
  a.download = `${fileName}.xlsx`
  a.style.display = 'none'
  a.dispatchEvent(event)
}

// 打印
export function lodopPrint(printName) {
  const LODOP = getLodop()
  if (!LODOP) {
    return
  }
  LODOP.PRINT_INIT(printName)
  LODOP.SET_PRINT_PAGESIZE(0, '', '', 'A4')
  LODOP.SET_PRINT_STYLE('Bold', '1')
  LODOP.SET_PRINT_STYLEA(0, 'FontSize', 19)
  const strBodyStyle = `<style>
                                .hidd{display: none}
                                table{ width: 100%;border-collapse:collapse; }
                                td{ font-size: 15px; border: 1px solid #000000;}
                                .text-center{ text-align: center; }
                          </style>`
  const strbody = `<body>${document.getElementById('exportId').outerHTML}</body>`
  const strHtml = strBodyStyle + strbody

  LODOP.ADD_PRINT_HTM(50, 40, '88%', '88%', strHtml)
  LODOP.ADD_PRINT_TEXT('98%', '50%', 100, 12, '第#页/共&页')
  LODOP.SET_PRINT_STYLEA(0, 'ItemType', 2)
  LODOP.SET_PRINT_STYLEA(0, 'Horient', 0)
  LODOP.SET_PRINT_STYLEA(0, 'Vorient', 0)
  LODOP.PREVIEW()
}
